// 全局通知函数
window.showNotification = function(message, type = 'info', duration = 3000) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.maxWidth = '300px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '8px';
    notification.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    notification.style.zIndex = '9999';
    notification.style.transition = 'transform 0.3s ease, opacity 0.3s ease';
    notification.style.transform = 'translateY(20px)';
    notification.style.opacity = '0';
    
    // 设置背景颜色
    if (type === 'success') {
        notification.style.backgroundColor = '#4caf50';
        notification.style.color = 'white';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#f44336';
        notification.style.color = 'white';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#ff9800';
        notification.style.color = 'white';
    } else {
        notification.style.backgroundColor = '#2196f3';
        notification.style.color = 'white';
    }
    
    // 设置消息内容
    notification.textContent = message;
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.style.transform = 'translateY(0)';
        notification.style.opacity = '1';
    }, 10);
    
    // 消失通知
    setTimeout(() => {
        notification.style.transform = 'translateY(20px)';
        notification.style.opacity = '0';
        
        // 移除元素
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, duration);
    
    return notification;
};

document.addEventListener('DOMContentLoaded', function() {
    console.log('页面已加载完成，应用程序初始化中...');
    
    // 检查是否存在登录状态
    if (window.ApiClient && window.ApiClient.User.isLoggedIn()) {
        console.log('用户已登录:', window.ApiClient.User.getCurrentUser());
    } else {
        console.log('用户未登录');
    }
    
    // 注册全局事件处理器
    document.body.addEventListener('click', function(e) {
        // 处理登录按钮
        if (e.target.matches('#loginBtn') || e.target.closest('#loginBtn')) {
            const loginModal = document.getElementById('loginModal');
            if (loginModal) {
                loginModal.style.display = 'block';
            }
        }
        
        // 处理关闭模态框按钮
        if (e.target.matches('.close-modal') || e.target.closest('.close-modal')) {
            const modal = e.target.closest('.modal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
    });
    
    // 通知函数
    function showNotification(message, type = 'success') {
        const notification = document.getElementById('notification');
        if (notification) {
            // 设置消息和类型
            notification.textContent = message;
            notification.className = `notification ${type}`;
            
            // 显示通知
            setTimeout(() => {
                notification.classList.add('show');
            }, 10);
            
            // 几秒后自动隐藏
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
    }
    
    // 将通知函数添加到全局 
    window.showNotification = showNotification;
    
    // 模态框操作
    const uploadBtn = document.getElementById('uploadBtn');
    const loginBtn = document.getElementById('loginBtn');
    const registerBtn = document.getElementById('registerBtn');
    const uploadModal = document.getElementById('uploadModal');
    const loginModal = document.getElementById('loginModal');
    const registerModal = document.getElementById('registerModal');
    const closeButtons = document.querySelectorAll('.close-button');
    const switchToRegister = document.getElementById('switchToRegister');
    const switchToLogin = document.getElementById('switchToLogin');
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');

    // 检查用户登录状态并更新UI
    function checkAuthStatus() {
        if (window.ApiClient && window.ApiClient.User.isLoggedIn()) {
            // 获取用户信息
            const userInfoStr = localStorage.getItem('user_info');
            if (userInfoStr) {
                try {
                    const userInfo = JSON.parse(userInfoStr);
                    
                    // 隐藏登录和注册按钮
                    if (loginBtn) loginBtn.style.display = 'none';
                    if (registerBtn) registerBtn.style.display = 'none';
                    
                    // 查找用户操作区域
                    const userActionsElem = document.querySelector('.user-actions');
                    if (userActionsElem) {
                        // 检查是否已经有用户个人资料UI
                        const existingProfileUI = userActionsElem.querySelector('.user-profile');
                        
                        if (!existingProfileUI) {
                            // 创建用户个人资料UI
                            const userProfileHTML = `
                                <div class="user-profile">
                                    <span class="username">${userInfo.username || '用户'}</span>
                                    <div class="user-dropdown">
                                        <a href="profile.html">个人中心</a>
                                        <a href="#">我的游戏</a>
                                        <a href="#">设置</a>
                                        <a href="#" id="logoutBtn">退出登录</a>
                                    </div>
                                </div>
                            `;
                            
                            // 添加到用户操作区域
                            userActionsElem.innerHTML = userProfileHTML;
                            
                            // 添加退出登录事件
                            const logoutBtn = document.getElementById('logoutBtn');
                            if (logoutBtn) {
                                logoutBtn.addEventListener('click', function(e) {
                                    e.preventDefault();
                                    handleLogout();
                                });
                            }
                        }
                    }
                } catch (error) {
                    console.error('解析用户信息失败:', error);
                    // 清除可能损坏的用户信息
                    localStorage.removeItem('user_info');
                }
            }
        }
    }
    
    // 处理退出登录
    function handleLogout() {
        if (window.ApiClient) {
            // 执行登出
            window.ApiClient.User.logout();
            
            // 刷新页面
            window.location.reload();
        }
    }
    
    // 初始化时检查登录状态
    checkAuthStatus();

    // 显示模态框
    function showModal(modal) {
        if (modal) {
            modal.style.display = 'block';
        }
    }

    // 隐藏模态框
    function hideModal(modal) {
        if (modal) {
            modal.style.display = 'none';
        }
    }

    // 显示上传游戏模态框
    if (uploadBtn) {
        uploadBtn.addEventListener('click', function() {
            // 检查用户是否已登录
            if (window.ApiClient && !window.ApiClient.User.isLoggedIn()) {
                // 如果未登录，显示登录模态框
                showModal(loginModal);
                // 显示提示消息
                if (loginForm) {
                    const noticeDiv = document.createElement('div');
                    noticeDiv.className = 'login-notice';
                    noticeDiv.style.backgroundColor = '#fff3cd';
                    noticeDiv.style.color = '#856404';
                    noticeDiv.style.padding = '10px';
                    noticeDiv.style.borderRadius = '4px';
                    noticeDiv.style.marginBottom = '15px';
                    noticeDiv.textContent = '请先登录才能上传游戏';
                    
                    // 添加到表单顶部
                    loginForm.insertBefore(noticeDiv, loginForm.firstChild);
                    
                    // 3秒后自动删除提示
                    setTimeout(() => {
                        if (noticeDiv.parentNode) {
                            noticeDiv.parentNode.removeChild(noticeDiv);
                        }
                    }, 3000);
                }
                return;
            }
            
            // 已登录，显示上传模态框
            showModal(uploadModal);
        });
    }

    // 显示登录模态框
    if (loginBtn) {
        loginBtn.addEventListener('click', function() {
            showModal(loginModal);
        });
    }

    // 显示注册模态框
    if (registerBtn) {
        registerBtn.addEventListener('click', function() {
            showModal(registerModal);
        });
    }

    // 关闭按钮事件
    closeButtons.forEach(function(btn) {
        btn.addEventListener('click', function() {
            // 获取最近的模态框
            const modal = this.closest('.modal');
            hideModal(modal);
        });
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal')) {
            hideModal(event.target);
        }
    });

    // 切换到注册模态框
    if (switchToRegister) {
        switchToRegister.addEventListener('click', function(e) {
            e.preventDefault();
            hideModal(loginModal);
            showModal(registerModal);
        });
    }

    // 切换到登录模态框
    if (switchToLogin) {
        switchToLogin.addEventListener('click', function(e) {
            e.preventDefault();
            hideModal(registerModal);
            showModal(loginModal);
        });
    }

    // 处理登录表单提交
    if (loginForm) {
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;
            
            // 验证输入
            if (!username || !password) {
                showFormMessage(loginForm, '请输入用户名和密码', 'error');
                return;
            }
            
            // 显示加载状态
            const submitBtn = loginForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '登录中...';
            
            try {
                // 调用登录API
                if (window.ApiClient) {
                    const response = await window.ApiClient.User.login(username, password);
                    
                    // 保存token
                    if (response.token) {
                        localStorage.setItem('auth_token', response.token);
                        
                        // 保存用户信息
                        if (response.user) {
                            localStorage.setItem('user_info', JSON.stringify(response.user));
                        }
                        
                        // 显示成功消息
                        showFormMessage(loginForm, '登录成功！', 'success');
                        
                        // 显示全局通知
                        if (window.showNotification) {
                            window.showNotification(`欢迎回来，${response.user?.username || '用户'}！`, 'success');
                        }
                        
                        // 更新UI
                        checkAuthStatus();
                        
                        // 2秒后关闭模态框并刷新页面
                        setTimeout(() => {
                            hideModal(loginModal);
                            
                            // 检查是否需要刷新页面
                            const needRefresh = loginForm.getAttribute('data-refresh') === 'true';
                            if (needRefresh) {
                                window.location.reload();
                            }
                        }, 1500);
                    } else {
                        showFormMessage(loginForm, '登录失败：服务器响应无效', 'error');
                    }
                } else {
                    showFormMessage(loginForm, '登录功能暂时不可用', 'error');
                }
            } catch (error) {
                console.error('登录失败:', error);
                showFormMessage(loginForm, error.message || '登录失败，请稍后再试', 'error');
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalBtnText;
            }
        });
    }
    
    // 处理注册表单提交
    if (registerForm) {
        registerForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const username = document.getElementById('registerUsername').value;
            const email = document.getElementById('registerEmail').value;
            const password = document.getElementById('registerPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 验证输入
            if (!username || !email || !password) {
                showFormMessage(registerForm, '请填写所有必填字段', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showFormMessage(registerForm, '两次输入的密码不一致', 'error');
                return;
            }
            
            // 显示加载状态
            const submitBtn = registerForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.textContent = '注册中...';
            
            try {
                // 调用注册API
                if (window.ApiClient) {
                    const userData = {
                        username,
                        email,
                        password
                    };
                    
                    const response = await window.ApiClient.User.register(userData);
                    
                    // 注册成功
                    if (response.success) {
                        // 显示成功消息
                        showFormMessage(registerForm, '注册成功！请登录', 'success');
                        
                        // 2秒后切换到登录模态框
                        setTimeout(() => {
                            hideModal(registerModal);
                            showModal(loginModal);
                            
                            // 自动填充用户名
                            const loginUsernameInput = document.getElementById('loginUsername');
                            if (loginUsernameInput) {
                                loginUsernameInput.value = username;
                            }
                        }, 1500);
                    } else {
                        showFormMessage(registerForm, '注册失败：' + (response.message || '未知错误'), 'error');
                    }
                } else {
                    showFormMessage(registerForm, '注册功能暂时不可用', 'error');
                }
            } catch (error) {
                console.error('注册失败:', error);
                showFormMessage(registerForm, error.message || '注册失败，请稍后再试', 'error');
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalBtnText;
            }
        });
    }
    
    // 显示表单消息
    function showFormMessage(form, message, type = 'success') {
        // 移除现有消息
        const existingMessage = form.querySelector('.form-message');
        if (existingMessage) {
            existingMessage.remove();
        }
        
        // 创建消息元素
        const messageDiv = document.createElement('div');
        messageDiv.className = `form-message ${type}`;
        messageDiv.textContent = message;
        
        // 设置样式
        if (type === 'success') {
            messageDiv.style.backgroundColor = '#d4edda';
            messageDiv.style.color = '#155724';
        } else {
            messageDiv.style.backgroundColor = '#f8d7da';
            messageDiv.style.color = '#721c24';
        }
        
        messageDiv.style.padding = '10px';
        messageDiv.style.borderRadius = '4px';
        messageDiv.style.marginBottom = '15px';
        
        // 添加到表单顶部
        form.insertBefore(messageDiv, form.firstChild);
        
        // 自动移除消息
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 3000);
    }
});